import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import '../models/learning_item.dart';
import '../models/category_service.dart';
import '../models/learning_data_service.dart';
import '../models/recommendation_service.dart';
import '../models/user_preference.dart';
import '../models/shared_recommendation_service.dart';
import 'main_screen.dart';

class CategoryScreen extends StatefulWidget {
  const CategoryScreen({super.key});

  @override
  State<CategoryScreen> createState() => _CategoryScreenState();
}

class _CategoryScreenState extends State<CategoryScreen> {
  List<LearningItem> _allItems = [];
  bool _isLoading = true;

  // 用户偏好
  UserPreference _userPreference = UserPreference();
  
  // 选择的筛选条件
  int? _selectedGrade;
  String? _selectedSubject;
  String? _selectedModule;

  List<String> _subjects = [];
  List<String> _modules = [];

  @override
  void initState() {
    super.initState();
    // 添加监听器
    SharedRecommendationService.instance.addListener(_onRecommendationUpdated);
    _loadItems();
  }

  @override
  void dispose() {
    // 移除监听器
    SharedRecommendationService.instance.removeListener(_onRecommendationUpdated);
    super.dispose();
  }

  void _onRecommendationUpdated() {
    // 当共享推荐数据更新时，刷新UI
    setState(() {
      // 状态会在build方法中从SharedRecommendationService获取最新数据
    });
  }

  void _loadItems() async {
    try {
      final items = await LearningDataService.loadLearningItems();
      SharedRecommendationService.instance.updateAllItems(items);
      setState(() {
        _allItems = items;
        _subjects = CategoryService.getAllSubjects(items);
        _modules = CategoryService.getAllModules(items);
        _isLoading = false;
      });
      
      // 初始推荐
      _generateRecommendations();
    } catch (e) {
      print('Error loading items: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  /// 生成推荐内容
  void _generateRecommendations() async {
    // 更新用户偏好
    _userPreference = SharedRecommendationService.instance.updateUserPreferenceFromSelection(
      _userPreference,
      _selectedGrade,
      _selectedSubject,
      _selectedModule,
    );
    
    // 生成推荐
    await SharedRecommendationService.instance.generateRecommendations();
    
    setState(() {
      // UI will rebuild with updated data from SharedRecommendationService
    });
  }

  /// 当用户选择筛选条件时调用
  void _onFilterChanged() {
    _generateRecommendations();
  }

  /// 当用户清除筛选条件时调用
  void _clearFilters() {
    setState(() {
      _selectedGrade = null;
      _selectedSubject = null;
      _selectedModule = null;
    });
    _generateRecommendations();
  }

  /// 当用户偏好更新时调用
  void _onPreferenceUpdated(UserPreference updatedPreference) {
    setState(() {
      _userPreference = updatedPreference;
    });
    // 可以选择是否立即重新生成推荐
    // _generateRecommendations();
  }

  /// 完成选择并返回
  void _finishSelection() {
    Navigator.pop(context, _userPreference);
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    // 从共享服务获取推荐数据
    final recommendedItems = SharedRecommendationService.instance.recommendedItems;

    return Scaffold(
      appBar: AppBar(
        title: const Text('智能推荐学习'),
        actions: [
          IconButton(
            icon: const Icon(Icons.check),
            onPressed: _finishSelection,
            tooltip: '完成选择',
          ),
        ],
      ),
      body: Column(
        children: [
          // 筛选区域
          Container(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '偏好设置（将影响推荐结果）',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 16),
                
                // 年级选择
                const Text('年级'),
                DropdownButtonFormField<int>(
                  value: _selectedGrade,
                  hint: const Text('请选择年级'),
                  isExpanded: true,
                  items: [
                    const DropdownMenuItem(
                      value: null,
                      child: Text('不限'),
                    ),
                    ...CategoryService.getAllGrades().map((grade) {
                      return DropdownMenuItem(
                        value: grade,
                        child: Text('$grade年级'),
                      );
                    }).toList(),
                  ],
                  onChanged: (value) {
                    setState(() {
                      _selectedGrade = value;
                    });
                    _onFilterChanged();
                  },
                ),
                const SizedBox(height: 16),
                
                // 学科选择
                const Text('学科'),
                DropdownButtonFormField<String>(
                  value: _selectedSubject,
                  hint: const Text('请选择学科'),
                  isExpanded: true,
                  items: [
                    const DropdownMenuItem(
                      value: null,
                      child: Text('不限'),
                    ),
                    ..._subjects.map((subject) {
                      return DropdownMenuItem(
                        value: subject,
                        child: Text(subject),
                      );
                    }).toList(),
                  ],
                  onChanged: (value) {
                    setState(() {
                      _selectedSubject = value;
                    });
                    _onFilterChanged();
                  },
                ),
                const SizedBox(height: 16),
                
                // 模块选择
                const Text('模块'),
                DropdownButtonFormField<String>(
                  value: _selectedModule,
                  hint: const Text('请选择模块'),
                  isExpanded: true,
                  items: [
                    const DropdownMenuItem(
                      value: null,
                      child: Text('不限'),
                    ),
                    ..._modules.map((module) {
                      return DropdownMenuItem(
                        value: module,
                        child: Text(module),
                      );
                    }).toList(),
                  ],
                  onChanged: (value) {
                    setState(() {
                      _selectedModule = value;
                    });
                    _onFilterChanged();
                  },
                ),
              ],
            ),
          ),
          
          // 推荐结果区域
          Expanded(
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '为您推荐 ${recommendedItems.length} 个学习内容',
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      IconButton(
                        icon: const Icon(Icons.refresh),
                        onPressed: _generateRecommendations,
                        tooltip: '刷新推荐',
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  Expanded(
                    child: recommendedItems.isEmpty
                        ? const Center(
                            child: Text('暂无推荐内容'),
                          )
                        : ListView.builder(
                            itemCount: recommendedItems.length,
                            itemBuilder: (context, index) {
                              final item = recommendedItems[index];
                              return Card(
                                margin: const EdgeInsets.symmetric(vertical: 4),
                                child: ListTile(
                                  title: Text(item.title),
                                  subtitle: Text(
                                    '${item.grade}年级 · ${item.subject} · ${item.module}',
                                  ),
                                  trailing: Icon(
                                    _getIconForContentType(item.type),
                                    color: Colors.blue,
                                  ),
                                  onTap: () {
                                    // 点击单个项目进入学习模式
                                    print('点击了 ${item.title}');
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) => MainScreen(initialIndex: index),
                                      ),
                                    );
                                  },

                                ),
                              );
                            },
                          ),
                  ),
                  const SizedBox(height: 16),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: () {
                        if (recommendedItems.isNotEmpty) {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const MainScreen(initialIndex: 0),
                            ),
                          );
                        }
                      },
                      child: const Text('开始学习所有推荐内容'),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  IconData _getIconForContentType(ContentType type) {
    switch (type) {
      case ContentType.knowledge:
        return Icons.school;
      case ContentType.question:
        return Icons.question_answer;
      case ContentType.poem:
        return Icons.auto_stories;
      case ContentType.math:
        return Icons.calculate;
      default:
        return Icons.help;
    }
  }
}